package com.linkhub.oms.admin.modules.order.domain.vo;

import cn.hutool.core.collection.CollUtil;
import com.linkhub.oms.common.util.QtStreamUtil;
import com.linkhub.oms.common.util.json.QtFastjsonUtil;
import com.linkhub.oms.data.sync.api.wms.domain.response.StockOutBatchCreateResponse;
import com.linkhub.oms.data.sync.api.yunexpress.domain.response.CreateOrderResponse;
import com.linkhub.oms.entity.OrderEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jaycle
 * @version 1.0.0
 * @Description EmployeeOrderPushToWmsResultVO.java
 * @createTime 2024/07/06 14:41
 */
@Data
@ApiModel("订单推送结果对象")
public class EmployeeOrderPushToWmsResultVO implements Serializable{

    @ApiModelProperty("成功数量")
    private int successTotal;

    @ApiModelProperty("失败数量，数量 > 0 才有失败原因")
    private int failTotal;

    @ApiModelProperty("失败原因")
    private String failReason;

    public static EmployeeOrderPushToWmsResultVO createResult( List<OrderEntity> pendingPushToWmsOrders, List<StockOutBatchCreateResponse.Order> orderList ) {
        EmployeeOrderPushToWmsResultVO vo = new EmployeeOrderPushToWmsResultVO();
        StringBuilder failReason = new StringBuilder();


        if (CollUtil.isNotEmpty(orderList)) {

            // 创建一个 sysOrderId 到 orderNumber 的映射
            Map<String, String> orderIdToOrderNumberMap = pendingPushToWmsOrders.stream()
                    .collect(Collectors.toMap(OrderEntity::getSysOrderId, OrderEntity::getOrderNumber));
            orderList.forEach(order -> {
                String orderNumber = orderIdToOrderNumberMap.get(order.getDeliveryOrderCode());
                String message = order.getMessage();
                if (orderNumber != null && message != null) {
                    failReason.append(String.format("The orderNumber [%s] forecast failed, reason: [%s]%n",
                            orderNumber, message));
                }
            });
            vo.setSuccessTotal(0);
            vo.setFailTotal(pendingPushToWmsOrders.size());
            vo.setFailReason(failReason.toString());
        } else {
            vo.setSuccessTotal(pendingPushToWmsOrders.size());
            vo.setFailTotal(0);
        }

        return vo;
    }
}
